package pl.edu.pb.wi.cookbook.controller;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import pl.edu.pb.wi.cookbook.entity.Category;
import pl.edu.pb.wi.cookbook.entity.Cookbook;
import pl.edu.pb.wi.cookbook.entity.Recipe;
import pl.edu.pb.wi.cookbook.form.SearchForm;
import pl.edu.pb.wi.cookbook.service.CategoryService;
import pl.edu.pb.wi.cookbook.service.CookbookService;
import pl.edu.pb.wi.cookbook.service.RecipeService;

@Controller
public class SearchController {
    private static final Logger log = Logger.getLogger(SearchController.class
            .getName());
    private RecipeService recipeService;
    private CategoryService categoryService;
    private CookbookService cookbookService;

    @Autowired
    public SearchController(RecipeService recipeService,
            CategoryService categoryService, CookbookService cookbookService) {
        this.recipeService = recipeService;
        this.categoryService = categoryService;
        this.cookbookService = cookbookService;
    }

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public String search(@ModelAttribute("searchForm")
    @Valid
    SearchForm form, Model model) {
        if (form == null || form.getQuery().isEmpty())
            return "main";

        try {
            List<Category> catList = categoryService.search(form.getQuery());
            List<Recipe> recList = recipeService.search(form.getQuery());
            List<Cookbook> bookList = cookbookService.search(form.getQuery());

            int count = 0;
            if (catList != null)
                count += catList.size();
            if (recList != null)
                count += recList.size();
            if (bookList != null)
                count += bookList.size();

            model.addAttribute("resultCount", count);
            model.addAttribute("categories", catList);
            model.addAttribute("recipes", recList);
            model.addAttribute("cookbooks", bookList);

            return "search";
        } catch (Exception e) {
            log.info(String.format("Problem with search. Exception: %s",
                    e.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));

            return "message";
        }
    }
}
